#include "net.h"

int main()
{
	int newfd;
	int fd;
	struct sockaddr_in soc;

	//创建套接字
	if(( fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		perror("socket");
		exit(1);

	}

	//填充ip 和端口
	soc.sin_family = AF_INET;
	soc.sin_port = htons(PORT);
	soc.sin_addr.s_addr = htonl(INADDR_ANY);
	//绑定
	if(( bind(fd, (struct sockaddr *)&soc, sizeof(soc))) < 0)
	{
		perror("bind");
		exit(1);
	}

	//把被动改为主动
	if( (listen(fd, BACKLOG)) < 0)
	{
		perror("listen");
		exit(1);
	}
	printf("服务器启动成功\n");

	//阻塞等待客户端连接

	struct sockaddr_in cin;
	socklen_t addrlen = sizeof (cin);
	if( (newfd = accept(fd, (struct sockaddr *)&cin, &addrlen)) < 0)
	{
		perror("accept");
		exit(1);
	}
	printf("连接成功\n");

	//读写数据
	int ret = -1;
	char buf[BUFSI];
	while(1)
	{
		bzero(buf, BUFSI);
		do
		{
			ret = read(newfd, buf, BUFSI-1);
		}while(ret < 0 && errno == EINTR);

		if(ret < 0)
		{
			perror("ret");
			exit(1);
		}

		if(!ret)
		{
			break;	//客户端关闭了
		}
		printf("read: %s", buf);
	}

	//关闭资源
	close(newfd);
	close(fd);
	return 0;
}
